package renguanyu.app.auth4fx.controller.user;

import javafx.concurrent.Task;
import javafx.scene.control.CheckBox;
import renguanyu.app.auth4fx.model.user.UserRoleDto;
import renguanyu.app.auth4fx.service.user.UserRoleService;
import renguanyu.app.auth4fx.view.user.UserRoleListView;


import java.util.List;
import java.util.stream.Collectors;

public class UserRoleListDeleteController extends Task<Void> {

    private UserRoleListView userRoleListView;
    public UserRoleListDeleteController(UserRoleListView userRoleListView) {
        this.userRoleListView = userRoleListView;
    }

    public void execute() {
        System.out.println("UserRoleListDelete.execute");
        Thread thread = new Thread(this);
        thread.setDaemon(true);
        thread.start();
    }

    private int rows = 0;
    List<CheckBox> rightSelectedCheckBoxes;
    @Override
    protected Void call() {
        System.out.println("UserRoleListDelete.call");
        UserRoleDto userRoleDto = buildUserRoleDto();
        rows = UserRoleService.deleteUserRoleList(userRoleDto);
        return null;
    }

    private UserRoleDto buildUserRoleDto() {
        rightSelectedCheckBoxes = userRoleListView.rightCheckBoxContainer.getChildren().stream().map(
            node -> (CheckBox) node
        ).filter(CheckBox::isSelected).collect(Collectors.toList());
        List<String> ids = rightSelectedCheckBoxes.stream().map(e -> e.getProperties().get("id").toString()).collect(Collectors.toList());
        UserRoleDto userRoleDto = new UserRoleDto();
        userRoleDto.setIds(ids);
        return userRoleDto;
    }

    @Override
    protected void running() {
        System.out.println("UserRoleListDelete.running");
    }

    @Override
    protected void succeeded() {
        System.out.println("UserRoleListDelete.succeeded");
        if(rows >= 1){
            userRoleListView.leftCheckBoxContainer.getChildren().removeAll(rightSelectedCheckBoxes);
            rightSelectedCheckBoxes.forEach(checkBox -> {
                userRoleListView.leftCheckBoxContainer.getChildren().add(checkBox);
            });
        }
    }

    @Override
    protected void failed() {
        System.out.println("RoleInfoSave.failed");
    }
}
